from zipfile import ZipFile
import toml, json, api, os, shutil, time, hashlib

class ModFile:
    def __init__(self, filename, gamever = "") -> None:
        self.jar = ZipFile(filename, 'r')
        self.mod = api.Mod("", "", gamever)
        for i in self.jar.infolist():
            if i.filename == "META-INF/mods.toml":
                self.mod.loader = "forge"
                break
            elif i.filename == "fabric.mod.json":
                self.mod.loader = "fabric"
                break
        else:
            self.mod.loader = "unknown"
        
        if self.mod.loader == "forge":
            config = toml.loads(self.jar.read("META-INF/mods.toml").decode('utf-8'))
            self.mod.modname = config["mods"][0]["modId"]
            if "displayName" in config["mods"][0].keys():
                self.mod.translate_name = config["mods"][0]["displayName"]
            self.mod.mod_version = input("enter mod version "+self.jar.filename+" --- ")
            if self.mod.game_version == "":
                self.mod.game_version = input("enter mod game version "+self.jar.filename+" --- ")
            if "authors" in config["mods"][0].keys():
                self.mod.authors = config["mods"][0]["authors"]
            if "description" in config["mods"][0].keys():
                self.mod.description = config["mods"][0]["description"]
            self.mod.rebuild()
        elif self.mod.loader == "fabric":pass
    
    def upload(self):
        self.serveroot = "./serveroot"
        try:
            os.makedirs(os.path.join(self.serveroot, "mods", self.mod.modname))
        except FileExistsError:
            pass
        shutil.copy(self.jar.filename, self.mod.get_file(self.serveroot))

# gamever = input("enter game version> ")
# if gamever == "":
#     for i in os.listdir("mods"):
#         m = ModFile(f"mods/{i}")
#         m.upload()
# else:
#     for i in os.listdir("mods"):
#         m = ModFile(f"mods/{i}", gamever)
#         m.upload()

# config = api.File(".\serveroot\packages\ymods\ymods-latest-1.20.1.pack").readJson()
# for i in os.listdir(".\serveroot\mess_mods"):
#     config["mess_mods"].append(i)
# api.File(".\serveroot\packages\ymods\ymods-latest-1.20.1.pack").writeJson(config)

class PackageBuilder:
    def __init__(self) -> None:
        self.config = {
            "id": time.time_ns(),
            "name": "",
            "pack_version": "",
            "game_version": "",
            "mods": [],
            "mess_mods": [],
            "files": [],
            "dirs": []
        }
    
    def name(self, name):
        self.config["name"] = name
        return self
    
    def packv(self, v):
        self.config["pack_version"] = v
        return self
    
    def gamev(self, v):
        self.config["game_version"] = v
        return self
    
    def mod(self, n, v1, v2):
        self.config["mods"].append({"name": n, "mod_version": v1, "game_version": v2})
        return self
    
    def mods(self, s):
        for i in s:
            n, v1, v2 = i
            self.mod(n, v1, v2)
        return self
    
    def mess_mod(self, file):
        self.config["mess_mods"].append(file)
        return self
    
    def mess_mods(self, files):
        for i in files:
            self.mess_mod(i)
        return self
    
    def file(self, n, t):
        self.config["files"].append({"name": n, "target": t})
        return self
    
    def files(self, s):
        for i in s:
            n,t = i
            self.file(n, t)
        return self
    
    def dir(self, n, t):
        self.config["dirs"].append({"name": n, "target": t})
        return self
    
    def dirs(self, s):
        for i in s:
            n,t = i
            self.dir(n, t)
        return self

    def build(self):
        f = api.File(f"./serveroot/packages/{self.config['name']}/{self.config['name']}-{self.config['pack_version']}-{self.config['game_version']}.pack")
        f.create()
        f.writeJson(self.config)

        sql = api.SqliteMain("test.db")
        sql.create_table(self.config['id'], [("id", api.SqliteType.INT + api.SqliteType.PRIMARY_KEY + api.SqliteType.AUTOINCREMENT),
                                               ("name", api.SqliteType.TEXT + api.SqliteType.UNIQUE),
                                               ("md5", api.SqliteType.TEXT)])
        for i in self.config["mess_mods"]:
            f = api.File(f"./serveroot/mess_mods/{i}")
            h = hashlib.md5(f.read()).hexdigest()
            sql.insert_into(self.config["id"], [("name", i), ("md5", h)])
        for i in self.config["files"]:
            f = api.File(f"./serveroot/packages/{self.config['name']}/files/{i}")
            h = hashlib.md5(f.read()).hexdigest()
            sql.insert_into(self.config["id"], [("name", i), ("md5", h)])
        
        sql.close()
        return f.path

PackageBuilder().name("ymods").packv("latest").gamev("1.20.1").mess_mods(os.listdir('serveroot/mess_mods')).build()

# main = api.SqliteMain("test.db")
# print(main.select_all("Industrial Revolution 2"))
# main.close()
